package com.hotely5d.service;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.hotely5d.dao.MemberMapper;
import com.hotely5d.entity.Admin;
import com.hotely5d.entity.Member;
import com.hotely5d.entity.model.Result;
import com.hotely5d.entity.model.StatusCode;
import com.hotely5d.entity.query.LoginQuery;
import com.hotely5d.utils.JWTUtils;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Transactional
public class MemberService {

    @Autowired
    private MemberMapper memberMapper;

    public List<Member> findAll() {
        // 只查询未删除的用户
        return memberMapper.selectList(new EntityWrapper<Member>().eq("deleted", 0));
    }

    public Page<Member> search(Page<Member> page,Member member) {
        return page.setRecords( memberMapper.selectPage(page,getEntityWrapper(member)));
    }

    public List<Member> search(Member member) {
        return memberMapper.selectList(getEntityWrapper(member));
    }

    //条件构造器
    private EntityWrapper<Member> getEntityWrapper(Member member){
        EntityWrapper<Member> entityWrapper = new EntityWrapper<>();
        // 只查询未删除的用户
        entityWrapper.eq("deleted", 0);
        if(null != member){
            if(!StringUtils.isEmpty(member.getUsername())){
                entityWrapper.like("username",String.valueOf(member.getUsername()));
            }
            if(!StringUtils.isEmpty(member.getPassword())){
                entityWrapper.like("password",String.valueOf(member.getPassword()));
            }
            if(!StringUtils.isEmpty(member.getName())){
                entityWrapper.like("name",String.valueOf(member.getName()));
            }
            if(!StringUtils.isEmpty(member.getPhone())){
                entityWrapper.like("phone",String.valueOf(member.getPhone()));
            }
            if(!StringUtils.isEmpty(member.getIdcard())){
                entityWrapper.like("idcard",String.valueOf(member.getIdcard()));
            }
            if(!StringUtils.isEmpty(member.getHead())){
                entityWrapper.like("head",String.valueOf(member.getHead()));
            }
        }
        return entityWrapper;
    }

    public void modify(Member member) {
        memberMapper.updateById(member);
    }

    public void add(Member member) {
        member.setCreateTime(new Date());
        // 设置默认值：未删除
        member.setDeleted(0);
        memberMapper.insert(member);
    }

    public Member findById(Integer id) {
        // 只查询未删除的用户
        List<Member> members = memberMapper.selectList(new EntityWrapper<Member>().eq("id", id).eq("deleted", 0));
        return members.isEmpty() ? null : members.get(0);
    }

    public void removeById(Integer id) {
        // 实现逻辑删除：将deleted字段设置为1
        Member member = new Member();
        member.setId(id);
        member.setDeleted(1);
        memberMapper.updateById(member);
    }

    public Result login(LoginQuery query) {
        // 只允许未删除的用户登录
        List<Member> list = memberMapper.selectList(new EntityWrapper<Member>()
                .eq("username", query.getUsername())
                .eq("password", query.getPassword())
                .eq("deleted", 0));
        if(list.size() == 0) return new Result(false, StatusCode.ERROR,"账号或密码错误");
        //返回Token
        Map<String,String> payloadMap = new HashMap<>();
        payloadMap.put("id",list.get(0).getId().toString());
        payloadMap.put("role","2");
        String token = JWTUtils.getToken(payloadMap);
        return new Result(true, StatusCode.OK,"登录成功",token);
    }

    public Result register(Member member) {
        // 检查用户名重复时只考虑未删除的用户
        List<Member> list = memberMapper.selectList(new EntityWrapper<Member>()
                .eq("username", member.getUsername())
                .eq("deleted", 0));
        if(list.size() != 0)return new Result(false, StatusCode.ERROR,"账号已被注册！");

        // 检查身份证号重复时只考虑未删除的用户
        list = memberMapper.selectList(new EntityWrapper<Member>()
                .eq("idcard", member.getIdcard())
                .eq("deleted", 0));
        if(list.size() != 0)return new Result(false, StatusCode.ERROR,"身份证号已被注册！");

        member.setCreateTime(new Date());
        // 设置默认值：未删除
        member.setDeleted(0);
        memberMapper.insert(member);
        return new Result(true, StatusCode.OK,"注册成功");
    }

    /**
     * 导出用户数据到Excel
     * @param member 查询条件
     * @param response HTTP响应
     */
    public void exportMemberData(Member member, HttpServletResponse response) {
        try {
            // 查询数据
            List<Member> memberList = search(member);

            // 创建工作簿
            Workbook workbook = new XSSFWorkbook();
            Sheet sheet = workbook.createSheet("用户信息");

            // 创建样式
            CellStyle headerStyle = workbook.createCellStyle();
            headerStyle.setFillForegroundColor(IndexedColors.BLUE.getIndex());
            headerStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
            headerStyle.setAlignment(HorizontalAlignment.CENTER);
            headerStyle.setVerticalAlignment(VerticalAlignment.CENTER);
            headerStyle.setBorderTop(BorderStyle.MEDIUM);
            headerStyle.setBorderBottom(BorderStyle.MEDIUM);
            headerStyle.setBorderLeft(BorderStyle.MEDIUM);
            headerStyle.setBorderRight(BorderStyle.MEDIUM);

            Font headerFont = workbook.createFont();
            headerFont.setColor(IndexedColors.WHITE.getIndex());
            headerFont.setBold(true);
            headerFont.setFontHeightInPoints((short) 12);
            headerStyle.setFont(headerFont);

            // 数据样式
            CellStyle dataStyle = workbook.createCellStyle();
            dataStyle.setAlignment(HorizontalAlignment.CENTER);
            dataStyle.setVerticalAlignment(VerticalAlignment.CENTER);
            dataStyle.setBorderTop(BorderStyle.THIN);
            dataStyle.setBorderBottom(BorderStyle.THIN);
            dataStyle.setBorderLeft(BorderStyle.THIN);
            dataStyle.setBorderRight(BorderStyle.THIN);

            // 文本数据样式（左对齐）
            CellStyle textStyle = workbook.createCellStyle();
            textStyle.setAlignment(HorizontalAlignment.LEFT);
            textStyle.setVerticalAlignment(VerticalAlignment.CENTER);
            textStyle.setBorderTop(BorderStyle.THIN);
            textStyle.setBorderBottom(BorderStyle.THIN);
            textStyle.setBorderLeft(BorderStyle.THIN);
            textStyle.setBorderRight(BorderStyle.THIN);

            // 日期格式样式
            CellStyle dateStyle = workbook.createCellStyle();
            dateStyle.setAlignment(HorizontalAlignment.CENTER);
            dateStyle.setVerticalAlignment(VerticalAlignment.CENTER);
            dateStyle.setBorderTop(BorderStyle.THIN);
            dateStyle.setBorderBottom(BorderStyle.THIN);
            dateStyle.setBorderLeft(BorderStyle.THIN);
            dateStyle.setBorderRight(BorderStyle.THIN);
            DataFormat format = workbook.createDataFormat();
            dateStyle.setDataFormat(format.getFormat("yyyy-mm-dd hh:mm:ss"));

            // 创建标题行
            Row headerRow = sheet.createRow(0);
            headerRow.setHeight((short) 600); // 设置行高

            String[] headers = {"用户ID", "账号", "姓名", "性别", "手机", "身份证", "头像", "注册时间"};
            for (int i = 0; i < headers.length; i++) {
                Cell cell = headerRow.createCell(i);
                cell.setCellValue(headers[i]);
                cell.setCellStyle(headerStyle);
            }

            // 填充数据
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            for (int i = 0; i < memberList.size(); i++) {
                Row row = sheet.createRow(i + 1);
                row.setHeight((short) 400);
                Member memberData = memberList.get(i);

                // 用户ID
                Cell cell0 = row.createCell(0);
                cell0.setCellValue(memberData.getId());
                cell0.setCellStyle(dataStyle);

                // 账号
                Cell cell1 = row.createCell(1);
                cell1.setCellValue(memberData.getUsername() != null ? memberData.getUsername() : "");
                cell1.setCellStyle(textStyle);

                // 姓名
                Cell cell2 = row.createCell(2);
                cell2.setCellValue(memberData.getName() != null ? memberData.getName() : "");
                cell2.setCellStyle(textStyle);

                // 性别
                Cell cell3 = row.createCell(3);
                String genderText = "";
                if (memberData.getGender() != null) {
                    genderText = memberData.getGender() == 1 ? "男" : "女";
                }
                cell3.setCellValue(genderText);
                cell3.setCellStyle(dataStyle);

                // 手机
                Cell cell4 = row.createCell(4);
                cell4.setCellValue(memberData.getPhone() != null ? memberData.getPhone() : "");
                cell4.setCellStyle(textStyle);

                // 身份证
                Cell cell5 = row.createCell(5);
                cell5.setCellValue(memberData.getIdcard() != null ? memberData.getIdcard() : "");
                cell5.setCellStyle(textStyle);

                // 头像
                Cell cell6 = row.createCell(6);
                cell6.setCellValue(memberData.getHead() != null ? memberData.getHead() : "");
                cell6.setCellStyle(textStyle);

                // 注册时间
                Cell cell7 = row.createCell(7);
                if (memberData.getCreateTime() != null) {
                    cell7.setCellValue(dateFormat.format(memberData.getCreateTime()));
                } else {
                    cell7.setCellValue("");
                }
                cell7.setCellStyle(dataStyle);
            }

            // 设置列宽
            sheet.setColumnWidth(0, 3000);   // 用户ID
            sheet.setColumnWidth(1, 4000);   // 账号
            sheet.setColumnWidth(2, 3500);   // 姓名
            sheet.setColumnWidth(3, 2500);   // 性别
            sheet.setColumnWidth(4, 4500);   // 手机
            sheet.setColumnWidth(5, 6000);   // 身份证
            sheet.setColumnWidth(6, 4000);   // 头像
            sheet.setColumnWidth(7, 5500);   // 注册时间

            // 冻结首行
            sheet.createFreezePane(0, 1);

            // 设置响应头
            String timestamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
            String fileName = "用户信息_" + timestamp + ".xlsx";

            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
            response.setCharacterEncoding("UTF-8");

            // 输出到响应流
            workbook.write(response.getOutputStream());
            workbook.close();

        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("导出Excel失败", e);
        }
    }
}
